from fastapi import APIRouter, WebSocket, WebSocketDisconnect, HTTPException
import json, base64, io
from app.config import settings
import edge_tts
from app.utils.logger import setup_logger
# 创建日志记录器
logger = setup_logger(__name__)
# 创建路由器
router = APIRouter(
    prefix="/eage",
    tags=["Eage"],
    responses={404: {"description": "Not found"}},
)

@router.websocket("/ws")
async def tts_websocket(websocket: WebSocket):
    await websocket.accept()
    try:
        # 接收客户端消息
        data = await websocket.receive_text()
        request_data = json.loads(data)
        
        # 获取请求参数
        api_key = request_data.get("api_key")
        voice = request_data.get("voice")
        text = request_data.get("text")
        
        # 验证参数
        if not voice or not text:
            
            await websocket.send_json({"error": "缺少必要参数"})
            return
        # 验证Eage TTS API密钥
        if api_key != settings.EAGE_TTS_API_KEY:
            logger.warning("无效的API密钥")
            await websocket.send_json({"error": "无效的API密钥"})
            return
        
        # 创建内存缓冲区而不是临时文件
        audio_buffer = io.BytesIO()
        
        try:
            # 使用edge-tts生成语音
            communicate = edge_tts.Communicate(text, voice)
            
            # 直接写入内存而不是文件
            async for chunk in communicate.stream():
                if chunk["type"] == "audio":
                    audio_buffer.write(chunk["data"])
            
            # 获取缓冲区的音频数据
            audio_data = audio_buffer.getvalue()
            
            # 转换为Base64
            audio_base64 = base64.b64encode(audio_data).decode("utf-8")
            
            # 发送结果
            await websocket.send_json({"audio": audio_base64})
            
        except Exception as e:
            logger.error(f"TTS生成失败: {str(e)}")
            await websocket.send_json({"error": f"TTS生成失败: {str(e)}"})
            
    except WebSocketDisconnect:
        logger.info("客户端断开连接")
    except Exception as e:
        logger.error(f"处理请求时发生错误: {str(e)}")
